package com.example.strategy;

import HslCommunication.Core.Types.OperateResultExOne;
import HslCommunication.Profinet.Siemens.SiemensS7Net;
import com.example.entity.DbBlock;
import com.example.enums.TypeEnum;
import com.example.exception.OpcException;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

/**
 * Copyright: Copyright (c) 2022
 *
 * <p>
 * Description: PLC 无符号的 16 位值数据进行转换
 *
 * @author LiuFeng
 * @version 2022/11/14 10:22
 * @since
 */
@Component
@Slf4j
public class NoSign16BitDataConvertStrategy implements PLCDataConvertStrategy {


    @Override
    public String convert(DbBlock dbBlock) {
//        String group = handleGroup(dbBlock);
//        byte[] data = PLCUtils.readPlcData(DaveArea.DB, Integer.parseInt(group), dbBlock.getLength(), Integer.parseInt(offset));
//        IntegerConverter integerConverter = new IntegerConverter();
//        Integer value = integerConverter.extract(Integer.class, data, 0, 0);
        SiemensS7Net siemensS7Net = null;

        try {
            siemensS7Net = getConnect();

            String offset = handleOffset(dbBlock);
            OperateResultExOne<Short> result = siemensS7Net
                    .ReadInt16(offset);
            if (result.IsSuccess) {
                return result.Content.toString();
            } else {
                log.error("读取数据失败，DB地址是：{}，buffer地址是：{}，错误原因是：{}", dbBlock.getAddrParams(), offset, result.Message);
                return null;
            }
        } catch (Exception ex) {
            log.error("读取：{}，数据异常：{}", dbBlock.getName(), ex.getMessage());
            throw new OpcException(ex);
        } finally {
            returnConnect(siemensS7Net);
        }
    }

    @Override
    public String getType() {
        return TypeEnum.NO_SIGN16_BIT.getType();
    }
}
